from django.shortcuts import render,redirect
from django.views import View
from django import http
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.contrib.auth import login
import logging
from django.urls import reverse
from nxh_mall.utils.response_code import RETCODE
from .models import OAuthQQUser

logger = logging.getLogger('django')
# Create your views here.

class QQAuthUserView(View):
    def get(self, request):
        code = request.GET.get('code')
        if code is None:
            return http.HttpResponseForbidden('获取code失败')
        # 使用code获取accesstoken
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            access_token = oauth.get_access_token(code)

            openid = oauth.get_open_id(access_token)
        except Exception as e:
            logger.error(str(e))
            return http.HttpResponseServerError('OAuth2.0认证失败')

        #查询openid如果存在，保持登录状态，否则弹出绑定用户页面
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            print('不存在')
            return render(request,'oauth_callback.html')
        else:
            #登录 从qq用户模型找到用户模型
            login(request,oauth_user.user)
            username = oauth_user.user.username
            #响应qq登录,回到首页
            url = reverse('contents:index')
            response = redirect(url)
            #设置cokkies和过期时间
            response.set_cookie('username', username, max_age=3600 * 24 * 15)

            return response


        return http

        pass


class QQAuthURLView(View):
    def get(self, request):
        next = request.GET.get('next')
        # 创建工具对象
        # oauth = OAuthQQ(client_id='appid',client_secret='appkey',redirect_uri='回调地址')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        # 生成qq登录地址
        login_url = oauth.get_qq_url()

        json_data = {'code': RETCODE.OK,
                     'errmsg': 'OK',
                     'login_url': login_url
                     }

        return http.JsonResponse(json_data)
